#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.views import View
from django.shortcuts import render
from django.http import JsonResponse
from repository import models
import xlrd
import os
import uuid
from django.shortcuts import HttpResponse,redirect,reverse


class IndexView(View):
    def get(self, request, *args, **kwargs):
        if not request.user.username:
            print("error")
            return redirect(reverse("login"))
        return render(request,"cmdbindex.html")


class CustomerView(View):
    def get(self, request, *args, **kwargs):
        customer_list = models.Customerinfo.objects.all()
        return render(request, "customer.html", locals())


class BillView(View):
    def get(self, request,*args,**kwargs):
        return render(request,"bill.html")

    def post(self, request, *args, **kwargs):
        excel_file = request.FILES.get("customer_excel")
        file_name = str(uuid.uuid4()) + "." + excel_file.name.rsplit('.', maxsplit=1)[1]
        excel_file_path = os.path.join('files', 'excels', file_name)
        with open(excel_file_path, 'wb') as f:
            for line in excel_file.chunks():
                f.write(line)
        try:
            # 获取excel表格对象
            excel_obj = xlrd.open_workbook(excel_file_path)
            # 获取表格对象的所有工作簿名称，存放至列表中
            sheet_names = excel_obj.sheet_names()
            # 取到第一张工作簿
            sheet_name_obj = excel_obj.sheet_by_name("销售表")
            # 获取当前工作簿的总行数
            # 循环获取每一行的数据
            for row in range(1, sheet_name_obj.nrows):
                row_data = sheet_name_obj.row_values(row,1)
                models.Customerinfo.objects.create(name=row_data[0],age=row_data[1],email=row_data[2],company=row_data[3])
            return redirect("/customer.html/")
        except Exception as e:
            return HttpResponse("上传失败，请重新上传")

